package pushclient

import (
	"encoding/json"
	"fmt"
	"gitee.com/mjun1833/buildnotification/config"
	"gitee.com/mjun1833/buildnotification/model"
	"io/ioutil"
	"net/http"
	"strings"
	"time"
)

var (
	instance *PushClient
)

type PushClient struct {
	httpClient *http.Client
}

func init() {
	c := &http.Client{
		Timeout: time.Duration(config.GetInstance().GetInt64("base.push.timeout")) * time.Second,
		Transport: &http.Transport{
			MaxIdleConns:        config.GetInstance().GetInt("base.push.maxConnect"),
			MaxIdleConnsPerHost: config.GetInstance().GetInt("base.push.maxConnect"),
		},
	}
	instance = &PushClient{httpClient: c}
}

func GetInstance() *PushClient {
	return instance
}

func (c *PushClient) PostSend(url, userIdentity string, obj interface{}) error {
	url = "http://127.0.0.1:4097/VIID/SubscribeNotifications"
	bodyBytes, _ := json.Marshal(obj)
	body := strings.NewReader(string(bodyBytes))

	req, err := http.NewRequest("POST", url, body)
	if err != nil {
		return err
	}

	req.Header.Set("User-Identify", userIdentity)
	req.Header.Set("Content-Type", "application/json")

	resp, err := c.httpClient.Do(req)
	if err != nil {
		return fmt.Errorf("send post request err:%v ", err.Error())
	}
	defer resp.Body.Close()

	respData := &model.ResponseStatusList{}
	respBody, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return fmt.Errorf("send post request err:%v ", err.Error())
	}

	if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusCreated && resp.StatusCode != http.StatusNoContent {
		return fmt.Errorf("send post request err code: %v,req: %v,resp:%v", resp.StatusCode, string(bodyBytes), string(respBody))
	}

	err = json.Unmarshal(respBody, respData)
	if err != nil {
		return fmt.Errorf("send post request unmarshal err req: %v,resp:%v", string(bodyBytes), string(respBody))
	}

	if len(respData.ResponseStatusListObject.ResponseStatusObject) == 0 && respData.ResponseStatusListObject.ResponseStatusObject[0].StatusCode != "0" {
		return fmt.Errorf("send post request err,req: %v,resp:%v", string(bodyBytes), string(respBody))
	}

	return nil
}
